layui.use(['laydate','table','layer'],function() {
    var layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        form = layui.form
    table = layui.table;

    function dateChange(num = 0,date = false) {
        if (!date) {
            date = new Date();//没有传入值时,默认是当前日期
            date = date.getFullYear() + '-' + (date.getMonth() + 1).toString().padStart(2, '0') + '-' + date.getDate().toString().padStart(2, '0');
        }
        date += " 00:00:00";//设置为当天凌晨12点
        date = Date.parse(new Date(date))/1000;//转换为时间戳
        date += (86400) * num;//修改后的时间戳
        var newDate = new Date(parseInt(date) * 1000);//转换为时间
        return newDate.getFullYear() + '-' + (newDate.getMonth() + 1).toString().padStart(2, '0') + '-' + (newDate.getDate()).toString().padStart(2, '0');
    }

    laydate.render({
        elem: '#startDate',
        format: "yyyy-MM-dd",
        value: dateChange(-31),
    });
    laydate.render({
        elem: '#endDate',
        format: "yyyy-MM-dd",
        value: new Date(),
    });


    // 选择客户
    $(document).on('click',"#openCustomerDialog",function openCustomerDialog(){
        var url  =  ctx+"/common/toSelectCustomerPage";
        var title="客户统计-客户选择";
        layui.layer.open({
            title : title,
            type : 2,
            area:["950px","700px"],
            maxmin:true,
            content : url
        });
    });

    $.ajax({
        type: "post",
        url: ctx + "/customer/allCustomers",
        success: function (data) {
            if (data !== null) {
                $.each(data, function (index, item) {
                    $("#customerId").append("<option value='" + item.id + "' >" + item.name + "</option>");
                });
            }
            //重新渲染
            form.render("select")
        }
    })


     table.render({
        elem: '#customerList',
         even: true,
        height: "auto",
        url:ctx+"/sale/list",
        page : true,
         pageSize: 6,
         limits : [6,12,24,48],
        id: "customerListTable",
        cols: [[
            {field: 'customerId', title: '客户Id', fixed: "left", width: 70, align: 'center'},
            {field: 'customerName', title: '客户姓名', fixed: "left", width: 90, align: 'center'},
            {field: 'saleDate', title: '日期', fixed: "left", width: 105, align: "center"},
            {field: 'saleNumber', title: '单号', fixed: "left",width: 145, align: "center"},
            {field: 'amountPayable', title: '销售金额', minWidth: 60, align: 'center'},
            {field: 'amountPaid', title: '已付金额', minWidth: 60, align: 'center'},
            {field: 'amountDiscounts', title: '优惠金额', minWidth: 60, align: 'center'},
            {field: 'amountNotPaid', title: '未付金额', minWidth: 60, align: 'center'},
            {field: 'state', title: '订单状态', minWidth: 60, align: 'center',templet:function (d){
                if(d.state==0){
                    return "未付款"
                }else if(d.state==1){
                    return "部分付款"
                }else {
                    return "已付款"
                }
            }},
            {field: 'userName', title: '制单员', minWidth: 60, align: 'center'},
            {field: 'remarks', title: '备注', minWidth: 60, align: 'center'},
            {title: '操作', Width: 100, templet: '#customerListBar', fixed: "right", align: "left"}
        ]]
    });


    table.render({
        elem: '#listGoods',
        height: "auto",
        // url:ctx+"/saleListGoods/list",
        page : false,
        // limits : [8,16,32,64],
        id: "listGoodsTable",
        cols: [[
            {field: 'code', title: '商品编码', width: 90,fixed: "left", align: "center"},
            {field: 'name', title: '商品名称', minWidth: 120, align: "center"},
            {field: 'typeName', title: '类别', width:85, align:'center'},
            {field: 'colorSize', title: '色号', width:58, fixed: "right",align:'center'},
            {field: 'unitName', title: '单位', width: 58,fixed: "right", align: 'center'},
            {field: 'price', title: '单价', minWidth: 100, align: 'center'},
            {field: 'num', title: '数量', minWidth: 100, align: 'center'},
            {field: 'total', title: '总金额', minWidth: 100, align: 'center'}
        ]]
    });

    // 销售单-支付记录明细展示
    table.render({
        elem: '#saleListPaymentList',
        height: "auto",
        page : false,
        id: "saleListPaymentListTable",
        cols: [[
            {field: "id", title: '编号', fixed: "true", width: 65},
            {field: "saleNumber", title: '销售单号', minWidth: 100, align: 'center'},
            {field: 'payDate', title: '支付日期', minWidth: 100, align: 'center'},
            {field: 'amountPaid', title: '支付金额', minWidth:100, align:'center'},
            {field: 'payType', title: '支付类型', minWidth: 100, align: 'center',templet:function (d){
                    if(d.payType==1){
                        return "自动生成"
                    }else{
                        return "手工结算"
                    }
                }},
            {field: 'userName', title: '结算者', minWidth:100, align:'center'},
            {field: 'updateUserName', title: '最后审核者', minWidth:100, align:'center'},
            {field: 'remarks', title: '备注', minWidth: 100, align: 'center'},
            {title: '操作', minWidth:120, templet:'#saleListPaymentListBar',fixed:"right",align:"center"}
        ]]
    });

    // 多条件搜索
    $(".search_btn").on("click",function(){
        table.reload("customerListTable",{
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                // customerId: $('select[name="customerId"] option:selected').val(),
                customerId: $("input[name='customerId']").val(),
                state: $('select[name="state"] option:selected').val(),
                startDate: $("input[name='startDate']").val(),
                endDate: $("input[name='endDate']").val(),
            }
        })
    });


    /**
     * 行监听
     */
    table.on("tool(customerList)", function (obj) {
        var layEvent = obj.event;
        if (layEvent === "search") {
            $.ajax({
                type:"post",
                url:ctx+"/saleListGoods/list",
                data:{
                    saleListId:obj.data.id
                },
                success:function (datas){
                    table.reload("listGoodsTable",{
                        data:datas.data
                    })
                }
            })
            $.ajax({
                type:"post",
                url:ctx+"/saleListPayment/list",
                data:{
                    saleListId:obj.data.id
                },
                success:function (datas){
                    table.reload("saleListPaymentListTable",{
                        data:datas.data
                    })
                }
            })
        }else if(layEvent === "check"){
            // console.log("amountPaid: " + obj.data.amountPaid);
            // console.log("amountNotPaid: " + obj.data.amountNotPaid);
            openAddOrUpdateSaleListPaymentListDialog(null, obj.data.id, obj.data.saleNumber, obj.data.amountNotPaid);
        }
    });


    /**
     * 行监听
     */
    table.on("tool(saleListPaymentList)", function(obj){
        var layEvent = obj.event;
        if(layEvent === "edit") {
            openAddOrUpdateSaleListPaymentListDialog(obj.data.id,null,null,obj.data.amountNotPaid);
        }else if(layEvent === "del") {
            layer.confirm('确定删除当前销售单付款记录？', {icon: 3, title: "销售单.付款记录管理"}, function (index) {
                $.post(ctx+"/saleListPayment/delete",{id:obj.data.id},function (data) {
                    if(data.code==200){
                        layer.msg("操作成功！");
                        tableIns.reload();
                    }else{
                        layer.msg(data.message, {icon: 5});
                    }
                });
            })
        }
    });

    // 打开 销售付款记录 添加|编辑 页面
    function openAddOrUpdateSaleListPaymentListDialog(id,saleListId,saleNumber,amountNotPaid){
        var url  =  ctx+"/saleListPayment/addOrUpdateSaleListPaymentPage";
        var title="销售单.付款记录管理-添加付款记录";
        if(id){
            url = url+"?id="+id+"&amountNotPaid="+amountNotPaid;
            title="销售单.付款记录管理-更新付款记录";
        } else {
            url = url+"?saleListId="+saleListId+"&saleNumber="+saleNumber+"&amountNotPaid="+amountNotPaid+"&payType=2";
        }
        layui.layer.open({
            title : title,
            type : 2,
            area:["600px","450px"],
            maxmin:true,
            content : url,
        });
    }


})

